package com.android.view.fragment.trade;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.model.entity.res.OrderResponse;
import com.android.model.entity.res.OrderResult;
import com.android.model.entity.res.SubmitOrderParamsEntity;
import com.android.model.info.LocalSp;
import com.android.model.net.TradeBizApi;
import com.android.presenter.iview.IResult;
import com.android.util.DateUtils;
import com.android.util.ToastUtil;
import com.android.view.activity.user.LoginActivity;
import com.android.view.widget.CustomerKeyboard;
import com.android.view.widget.PasswordEditText;
import com.mp.chart.utils.StringUtils;
import com.android.R;
import com.android.presenter.info.CancelOrderPresenter;
import com.android.presenter.info.OpenOrderPresenter;
import com.android.presenter.iview.ICancelOrderResultView;
import com.android.presenter.iview.IOpenOrderView;
import com.android.util.SimplePrompt;
import com.android.util.log.LogUtil;
import com.android.view.activity.trade.ALLOpenOrdersActivity;
import com.android.view.activity.user.TradePWDVerifySecurityActivity;
import com.android.view.fragment.base.BaseFragment;
import com.android.view.widget.CommonDialog;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author:  TenFace
 * date:    2017/9/27
 * description:
 */

public class TradeBuyFragment extends BaseFragment implements IOpenOrderView,
        ICancelOrderResultView,
        CustomerKeyboard.CustomerKeyboardClickListener,
        PasswordEditText.PasswordFullListener {

    //    @BindView(R.id.srl_movie)
//    SwipeRefreshLayout mSrlMovie;
    @BindView(R.id.llHaveOpenOrders)
    LinearLayout llHaveOpenOrders;
    @BindView(R.id.llDataEmptyView)
    LinearLayout llDataEmptyView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerViewBuy)
    RecyclerView recyclerViewBuy;
    @BindView(R.id.recyclerViewSell)
    RecyclerView recyclerViewSell;
    @BindView(R.id.tvInputPrice)
    TextView tvInputPrice;
    @BindView(R.id.tvInputAmount)
    TextView tvInputAmount;
    @BindView(R.id.tvTotalType)
    TextView tvTotalType;
    @BindView(R.id.tvDeposit)
    TextView tvDeposit;
    @BindView(R.id.tvPrice)
    TextView tvPrice;
    @BindView(R.id.tvAmount)
    TextView tvAmount;
    @BindView(R.id.tvResultPrice)
    TextView tvResultPrice;
    @BindView(R.id.tvLookMore)
    TextView tvLookMore;
    @BindView(R.id.tvLookAll)
    TextView tvLookAll;
    @BindView(R.id.btnTradeSell)
    Button btnTradeBuy;
    @BindView(R.id.etInputPrice)
    EditText etInputPrice;
    @BindView(R.id.etInputAmount)
    EditText etInputAmount;

    @BindColor(R.color.lite_blue)
    int colorBlue;
    @BindColor(R.color.green)
    int colorGreen;
    @BindColor(R.color.orange)
    int colorOrange;

    private String title;
    private String type;

    private CustomerKeyboard mCustomerKeyboard;
    private PasswordEditText mPasswordEt;
    private ImageView deleteDialog;
    private TextView forgetPWD;
    private CommonDialog.Builder passwordBuilder;

    private OpenOrderPresenter openOrderPresenter;
    private CancelOrderPresenter cancelOrderPresenter;
    private String ssoToken;
    private String accountId;
    private String session;
    private String orderTradeToken;

    public static TradeBuyFragment newInstance(String title, String type) {
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("type", type);
        TradeBuyFragment fragment = new TradeBuyFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        notifyOpenOrders();
        initButton();
    }

    @Override
    protected int setContentLayout() {
        return R.layout.fragment_trade_buy;
    }

    @Override
    protected void initView() {
        //设置下拉刷新的圆环变化颜色，蓝绿橙
//        mSrlMovie.setColorSchemeColors(colorBlue, colorGreen, colorOrange);

        initButton();

        openOrderPresenter = new OpenOrderPresenter(this);
        cancelOrderPresenter = new CancelOrderPresenter(this);

        title = getArguments().getString("title");
        type = getArguments().getString("type");

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getContext());
        linearLayoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager1);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);

        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getContext());
        linearLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerViewBuy.setLayoutManager(linearLayoutManager2);
        recyclerViewBuy.setHasFixedSize(true);
        recyclerViewBuy.setNestedScrollingEnabled(false);

        LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(getContext());
        linearLayoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerViewSell.setLayoutManager(linearLayoutManager3);
        recyclerViewSell.setHasFixedSize(true);
        recyclerViewSell.setNestedScrollingEnabled(false);

        tvInputPrice.setText(type);
        tvInputAmount.setText(title);
        tvTotalType.setText(type);
        tvDeposit.setText(type);
        tvPrice.setText("(" + type + ")");
        tvAmount.setText("(" + title + ")");

    }

    @Override
    protected void obtainData() {
        accountId = LocalSp.getInstance(getContext()).getAccountInfoId();
        orderTradeToken = LocalSp.getInstance(getContext()).getOrderTradeToken();
//        createTokenPresenter.createToken(getContext(), accountId, "ORDER", accountTradeToken);
        openOrderPresenter.getListOpenOrder(accountId, orderTradeToken);
    }

    @Override
    protected void initEvent() {

        etInputPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                displayTotalPrice();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                displayTotalPrice();
            }

            @Override
            public void afterTextChanged(Editable s) {
                displayTotalPrice();
            }
        });

        etInputAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                displayTotalPrice();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                displayTotalPrice();
            }

            @Override
            public void afterTextChanged(Editable s) {
                displayTotalPrice();
            }
        });

        InputFilter[] inputFilterArray = new InputFilter[1];
        inputFilterArray[0] = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                if (spanned.length() == 0 && charSequence.equals(".")) {
                    return "0.";
                }
                return null;
            }
        };
        etInputPrice.setFilters(inputFilterArray);
        etInputAmount.setFilters(inputFilterArray);

        tvLookMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.show("查看所有当前委托");
                startActivity(new Intent(getContext(), ALLOpenOrdersActivity.class));
            }
        });

        tvLookAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.show("查看所有当前委托");
                startActivity(new Intent(getContext(), ALLOpenOrdersActivity.class));
            }
        });

        btnTradeBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                verify();
                ssoToken = LocalSp.getInstance(getContext()).getSSOToken();
                if (!TextUtils.isEmpty(ssoToken)) {

                    if (TextUtils.isEmpty(etInputPrice.getText().toString())) {
                        ToastUtil.show("请输入价格");
                        return;
                    }

                    if (TextUtils.isEmpty(etInputAmount.getText().toString())) {
                        ToastUtil.show("请输入数量");
                        return;
                    }

                    SimplePrompt.getIntance().showLoadingMessage(getContext(), "下单中...", false);

                    final SubmitOrderParamsEntity params = getSubmitEntity();

                    TradeBizApi.getInstance().placeOrder(getContext(),
                            params,
                            null,
                            new PlaceOrderCallBack());
                } else {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }

            }
        });
    }

    @Override
    public void click(String number) {
        mPasswordEt.addPassword(number);
    }

    @Override
    public void delete() {
        mPasswordEt.deleteLastPassword();
    }

    @Override
    public void passwordFull(String password, int position) {
    }

    @Override
    public void passwordFull(String password) {
//        ToastUtil.show("密码是：" + password);
        SimplePrompt.getIntance().showLoadingMessage(getContext(), "下单中...", false);
        final SubmitOrderParamsEntity params = getSubmitEntity();
        TradeBizApi.getInstance().placeOrder(getContext(),
                params,
                password,
                new PlaceOrderCallBack());
        if (passwordBuilder != null) {
            passwordBuilder.dismiss();
        }
    }

    @Override
    public void orderOpenSuccess(List<OrderResult> orderResultList) {
        if (orderResultList != null) {
            LogUtil.e("orderOpenSuccess");
            TradeBuyAdapter tradeBuyAdapter = new TradeBuyAdapter(getContext(), orderResultList);
            recyclerView.setAdapter(tradeBuyAdapter);

            if (orderResultList.size() == 0) {
                dataIsNull();
            } else {
                dataNotNull();
            }
            tradeBuyAdapter.notifyDataSetChanged();

//            recyclerViewBuy.setAdapter(new OrderHistoryAdapter(getContext(), orderResultList));
//            recyclerViewSell.setAdapter(new OrderHistoryAdapter(getContext(), orderResultList));
        }
    }

    @Override
    public void orderOpenFail(int status, String desc) {

    }


    @Override
    public void orderCancelSuccess(OrderResult orderResult) {
        SimplePrompt.getIntance().dismiss();
        if (orderResult != null) {
            notifyOpenOrders();
            ToastUtil.show("取消委托单成功！");
        }
    }

    @Override
    public void orderCancelFail(int status, String desc) {
        SimplePrompt.getIntance().dismiss();
    }

    public class TradeBuyAdapter extends RecyclerView.Adapter<TradeBuyAdapter.TradeBuyHolder> {

        private Context mContext;
        private List<OrderResult> list;

        public TradeBuyAdapter(Context context, List<OrderResult> orderResultList) {
            super();
            this.mContext = context;
            this.list = orderResultList;
        }

        @Override
        public TradeBuyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_open_orders, null);
            TradeBuyHolder tradeBuyHolder = new TradeBuyHolder(view);
            return tradeBuyHolder;
        }

        @Override
        public void onBindViewHolder(TradeBuyHolder holder, final int position) {
            holder.tvSymbol.setText(list.get(position).getSymbol());
            holder.tvStatus.setText(list.get(position).getOrderStatus());
            holder.tvPrice.setText(String.valueOf(list.get(position).getLimitPrice()));
            holder.tvAmount.setText(String.valueOf(list.get(position).getOpenQuantity()));
            holder.tvOrderDateTime.setText(DateUtils.getDateToStringYMD(list.get(position).getCreatedAt()));
            holder.tvOrderTime.setText(DateUtils.getDateToStringHms(list.get(position).getCreatedAt()));
            holder.tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SimplePrompt.getIntance().showLoadingMessage(getContext(), "取消中...", false);
                    session = LocalSp.getInstance(getContext()).getOrderTradeSession("ORDER");
                    cancelOrderPresenter.cancelOrder(accountId, list.get(position).getOrderId(), session);
                }
            });
        }

        @Override
        public int getItemCount() {
            return 5;
        }

        class TradeBuyHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.tvSymbol)
            TextView tvSymbol;
            @BindView(R.id.tvStatus)
            TextView tvStatus;
            @BindView(R.id.tvPrice)
            TextView tvPrice;
            @BindView(R.id.tvAmount)
            TextView tvAmount;
            @BindView(R.id.tvOrderDateTime)
            TextView tvOrderDateTime;
            @BindView(R.id.tvOrderTime)
            TextView tvOrderTime;
            @BindView(R.id.tvCancel)
            TextView tvCancel;

            public TradeBuyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /***
     * 获取当前委托列表
     */
    private void notifyOpenOrders() {
        accountId = LocalSp.getInstance(getContext()).getAccountInfoId();
        orderTradeToken = LocalSp.getInstance(getContext()).getOrderTradeToken();
        LogUtil.e(accountId);
        LogUtil.e(orderTradeToken);
        if (!TextUtils.isEmpty(accountId) && !TextUtils.isEmpty(orderTradeToken)) {
            openOrderPresenter.getListOpenOrder(accountId, orderTradeToken);
        }
    }

    /***
     * 买入按钮初始化
     */
    private void initButton() {
        try {
            ssoToken = LocalSp.getInstance(getContext()).getSSOToken();
            if (!TextUtils.isEmpty(ssoToken)) {
                btnTradeBuy.setText("Buy");
            } else {
                btnTradeBuy.setText("Login");
            }
        } catch (Exception e) {
            e.printStackTrace();
            btnTradeBuy.setText("Login");
        }
    }

    /**
     * 获取提交时的实体
     *
     * @return 提交下单的信息
     */
    public SubmitOrderParamsEntity getSubmitEntity() {
        SubmitOrderParamsEntity entity = new SubmitOrderParamsEntity();
        entity.symbol = title + type;
        entity.orderType = "LIMIT";
        entity.orderSide = "BUY";
        entity.limitPrice = Double.parseDouble(etInputPrice.getText().toString());
        entity.quantity = Double.parseDouble(etInputAmount.getText().toString());
        return entity;
    }

    /***
     * 处理订单预估总价
     */
    private void displayTotalPrice() {
        try {
            String stockPriceStr = etInputPrice.getText().toString();
            String stockNumStr = etInputAmount.getText().toString();
            if (!TextUtils.isEmpty(stockPriceStr) && !TextUtils.isEmpty(stockNumStr)) {
                BigDecimal stockPriceBig = new BigDecimal(stockPriceStr);
                BigDecimal stockNumBig = new BigDecimal(stockNumStr);
                tvResultPrice.setText(StringUtils.strAddDotLast2(stockPriceBig.multiply(stockNumBig).toPlainString()));
            } else {
                tvResultPrice.setText("0.00");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }


    /**
     * 下单回调
     */
    private class PlaceOrderCallBack implements IResult<OrderResponse> {

        @Override
        public void success(OrderResponse data) {
            SimplePrompt.getIntance().dismiss();
            ToastUtil.show("下单成功");
            notifyOpenOrders();

        }

        @Override
        public void error(Object errorStatus, String msg) {
            LogUtil.e("msg=" + msg);
            SimplePrompt.getIntance().dismiss();

            if (msg.equals(TradeBizApi.RE_LOGIN)) {
                ToastUtil.show("登录失效，请退出重新登录");
            } else if (msg.equals(TradeBizApi.MESSAGE_10016)) {
                ToastUtil.show(msg);
            } else if (msg.equals(TradeBizApi.TRADE_PASSWORD_EXPIRED)) {
                //交易密码过期 弹出设置交易密码的窗体
                showDialog();
            } else if (msg.equals(TradeBizApi.SECURITY_VERIFY)) {
                //安全验证
                ToastUtil.show("您还未设置交易密码，无法交易");
            } else {
                //其他错误信息
                ToastUtil.show(msg);
            }
        }
    }

    private void showDialog() {
        //输入交易密码
        passwordBuilder = new CommonDialog.Builder(getContext());
        passwordBuilder.setView(R.layout.dialog_customer_keyboard).fullWidth().create().show();
        mPasswordEt = passwordBuilder.getView(R.id.password_edit_text);
        mCustomerKeyboard = passwordBuilder.getView(R.id.custom_key_board);
        deleteDialog = passwordBuilder.getView(R.id.deleteDialog);
        forgetPWD = passwordBuilder.getView(R.id.forgetPWD);
        mCustomerKeyboard.setOnCustomerKeyboardClickListener(this);
        mPasswordEt.setEnabled(false);
        mPasswordEt.setOnPasswordFullListener(this, 0);
        forgetPWD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), TradePWDVerifySecurityActivity.class));
            }
        });
        deleteDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordBuilder.dismiss();
            }
        });
    }

    /**
     * 数据为空
     */
    private void dataIsNull() {
        if (llHaveOpenOrders != null && llDataEmptyView != null) {
            llHaveOpenOrders.setVisibility(View.GONE);
            llDataEmptyView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 数据不为空view
     */
    private void dataNotNull() {
        if (llHaveOpenOrders != null && llDataEmptyView != null) {
            llHaveOpenOrders.setVisibility(View.VISIBLE);
            llDataEmptyView.setVisibility(View.GONE);
        }
    }

}
